package ltd.newbee.mall.config;

import com.alibaba.fastjson.JSON;
import ltd.newbee.mall.config.constant.Log;
import ltd.newbee.mall.dao.LogMapper;
import ltd.newbee.mall.entity.SysLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class LogAspect {
    @Autowired
    private LogMapper logMapper;

    @Around("@annotation(logAnnotation)")
    public Object logAround(ProceedingJoinPoint joinPoint, Log logAnnotation) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long execTime = System.currentTimeMillis() - startTime;

        SysLog sysLog = new SysLog();
        sysLog.setModule(logAnnotation.module());
        sysLog.setAction(logAnnotation.action());
        sysLog.setExecTime(execTime);
        sysLog.setCreateTime(new Date());

        if(logAnnotation.saveParams()) {
            sysLog.setParams(JSON.toJSONString(joinPoint.getArgs()));
        }
        if(logAnnotation.saveResult()) {
            sysLog.setResult(JSON.toJSONString(result));
        }

        logMapper.insertSelective(sysLog);
        return result;
    }
}

